# -*- coding: utf-8 -*-
from datetime import datetime

from django.http import QueryDict
from django.utils.deprecation import MiddlewareMixin

from gis.common import track_logging
from gis.common.exceptions import BizException
from itpay.core.agency.agency_service import get_agency_by_token

_LOGGER = track_logging.getLogger(__name__)


def get_client_ip(request):
    x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
    if x_forwarded_for:
        ip = x_forwarded_for
    else:
        ip = request.META.get("REMOTE_ADDR")
    return ip


class TrackLoggerMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """打印request进入时的log"""

        try:
            track_logging.clear_trace()

            request.DATA = QueryDict("")
            if request.method == "GET":
                body = request.META["QUERY_STRING"]
            else:
                body = request.body.decode()

            request.incoming_time = datetime.now()
            request.ip = get_client_ip(request)
            token = request.META.get(
                "HTTP_X_AUTH_TOKEN"
            )  # token被django转换成HTTP_TOKEN存放在META里面.
            request.user_dict = {}
            request.user_id = None

            if token:
                try:
                    user_dict = get_agency_by_token(token)
                    request.user_dict = user_dict
                    request.user_id = user_dict.get("id")
                except BizException:
                    pass

            user = request.user_dict and "{}({})".format(
                request.user_dict["id"], request.user_dict["user_name"]
            )
            _LOGGER.info(
                "{} - {}, USER: {}, DATA: {}, IP: {}".format(
                    request.method.upper(), request.path, user, body, request.ip
                )
            )
        except Exception:
            _LOGGER.exception("middleware process view fail")

    def process_exception(self, request, exception):
        pass

    def process_response(self, request, response):
        try:
            duration = int(
                (datetime.now() - request.incoming_time).total_seconds() * 1000
            )
            _LOGGER.info(
                "URL: {method}: {api_url}, Duration:{duration}".format(
                    method=request.method.upper(),
                    api_url=request.path,
                    duration=duration,
                )
            )
        except Exception:
            _LOGGER.exception("middleware process response fail")
        return response
